<?php
class NerdPass_Secure {
	private $td;
	private $key;
	private $iv;
	
	public function __construct($password = NULL, $keypass = NULL, $key = NULL) {
		$this->td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
		$this->iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), MCRYPT_DEV_URANDOM);
		$ks = mcrypt_enc_get_key_size($this->td);
		
		if ($key == NULL) {
			$keypass = substr($keypass, 0, 12);
			$key1 = hash('sha512', $password);
			$key2 = hash('sha512', $keypass);
			$key = substr($key1, 0, $ks / 2) . substr(strtoupper($key2), (round(strlen($key2) / 2)), $ks / 2);
			$key = substr($key . $key1 . $key2 . strtoupper($key1), 0, $ks);
			$this->key = $key;
		}
		else {
			$this->key = substr($key, 0, 32);
		}
	}
	
	public function decrypt($data) {
		if ($data == NULL) {
			return NULL;
		}
		mcrypt_generic_init($this->td, $this->key, $this->iv);
		$ddata = mdecrypt_generic($this->td, $data);
		mcrypt_generic_deinit($this->td);
		return $ddata;
	}
	
	public function encrypt($data) {
		if ($data == NULL) {
			return NULL;
		}
		mcrypt_generic_init($this->td, $this->key, $this->iv);
		$edata = mcrypt_generic($this->td, $data);
		mcrypt_generic_deinit($this->td);
		return $edata;
	}
	
	public static function create_key($input) {
		$password = hash('sha512', $input);
		$seed;
		for ($i = 1; $i <= mt_rand(128, 1024); $i++) {
			mt_srand();
			$seed = $seed . mt_rand(0, 12);
			mt_srand();
			usleep(mt_rand(1, 10));
		}
		
		// Create random key
		mt_srand($seed);
		$loop = mt_rand(1, 512);
		$len = strlen($password);
		for ($i = 0; $i <= $loop; $i++) {
			mt_srand();
			$r = mt_rand(1, $len);
			$s = $password[$r];
			if (ctype_alpha($s)) {
				if (ctype_upper($s)) {
					$password[$r] = strtolower($s);
				}
				else {
					$password[$r] = strtoupper($s);
				}
			}
			else {
				mt_srand();
				$add = mt_rand(0, 128);
				$new = $s + $add;
				$password[$r] = $new;
			}
		}
		return $password;
	}
	
	function __destruct() {
		mcrypt_module_close($this->td);
	}
}